<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_hb_bjmarathon')){
    class Api_hb_bjmarathon extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        // protected $_base_url = 'https://bmapi.pxene.com';
        protected $_base_url = 'https://www.bluemembers.com.cn/api';
        protected $_client_id = 'opc07e5ad3f3fe297e';
        protected $_client_secret = '931efbdc1ba967e8b72c9e4a15a07d46';

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('configmodel','m_config');
            $this->load->model('Bjmarathoncustomermodel','m_customer');
            $this->load->model('Bjmarathonlotterytimemodel','m_lottery_time');
            $this->load->database();

            header("Access-Control-Allow-Origin: *");

            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
            	$this->db->close();
                return;
            }
            $customer = $this->session->userdata('marathon_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }

        private function _getToken() {
            $this->load->driver('cache', array('adapter' => 'file'));
            $cache_file = 'token.cache';
            $content = $this->cache->get($cache_file);

            if(empty($content)) {
                $this->load->library('rest');
                $url = $this->_base_url.'/OAuth/Token';
                $content = $this->rest->post($url
                    ,array('client_id' => $this->_client_id
                        , 'client_secret' => $this->_client_secret
                        ,'scope' => 'basic'
                        ,'grant_type' => 'client_credentials'));
                $expires_in = $content->expires_in;
                $content = json_encode($content);
                $this->cache->save($cache_file,  $content,  $expires_in - 1000);
            }
            $content = json_decode($content,true);
            $token = $content['token_type'].' '.$content['access_token'];
            return $token;
        }

        public function test1() {
            // echo json_encode($this->_getMemberInfo('dcd03f4b-630b-4322-a911-ec278e566ed8'));
            echo json_encode($this->_getMemberInfo('D66DC427-FCEC-446C-8A7E-4622773F1709'));
        }

        public function test2() {
            // echo json_encode($this->_getMemberInfo('dcd03f4b-630b-4322-a911-ec278e566ed8'));
            $user_id = '481452b2-39dc-4b15-bb55-a4bfcc86def1';
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/CustomCard/GetUserCustomCardList?merchantType=1&userId='.$user_id;
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            echo json_encode($content);
        }

        public function test3() {
            // echo json_encode($this->_getMemberInfo('dcd03f4b-630b-4322-a911-ec278e566ed8'));
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/CustomCard/GetSummerCardList';
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            echo json_encode($content);
        }


        public function getToken() {
        	$token = $this->_getToken();
        	header('Content-Type: application/javascript');
        	echo 'var global_authorization="'.$token.'";';
        }

        private function _login($info) {
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/Account/DoLoginByPhone';
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url
                ,array('UserName' => $info['bluemember_phone']
                        ,'Captcha' => $info['captcha']
                        ,'CreatedPerson' => $this->input->post('source')));
            $content = json_decode(json_encode($content),true);
            if($content['code'] != 200) {
                $this->response->setDetail($content['msg']);
                $this->response->responseExit();
            }
            return $content;
        }

        private function _getMemberInfo($bluemember_user_id) {
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/Account/MemberInfo?id='.$bluemember_user_id;
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url
                ,array());
            $content = json_decode(json_encode($content),true);
            return $content;
        }

        private function _checkMember($member,$checkChezhu = false) {
            if(empty($member['Code']) || $member['Code'] != 200) {
                $this->response->setDetail('还不是Bluemembers用户!');
                $this->response->responseExit();
            }
            if($checkChezhu) {
                if(intval($member['Content']['SystemMType']) <= 1) {
                    $this->response->setDetail('还不是Bluemembers车主用户!');
                    $this->response->responseExit();
                }
            }
        }

        public function getCaptcha() {
            if(NOW > '2016-08-15 20:00:00') {
                $this->response->setDetail('活动已经结束，请您关注bluemembers的其他活动');
                $this->response->responseExit();
            }

            $this->validate->setRule('bluemember_phone','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(!preg_match("/^1\d{10}$/i", $info['bluemember_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/SMS/ValidateCode?phoneNumber='.$info['bluemember_phone'].'&num=4';
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url ,array());
            $content = json_decode(json_encode($content),true);

            if($content['Code'] != 200) {
                $this->response->setDetail($content['Message']);
                $this->response->responseExit();
            }

            $this->response->setSuccess();
            $this->response->responseExit();
        }

        public function initCustomer() {
            if(NOW > '2016-08-15 20:00:00') {
                $this->response->setDetail('活动已经结束，请您关注bluemembers的其他活动');
                $this->response->responseExit();
            }

            $this->validate->setRule('bluemember_phone','string');
            $this->validate->setRule('captcha','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $captcha = $info['captcha'];
            $tmp_arr = array(
                '666666' => '4d9a1c13-f9fb-41dd-859a-23d3a6eb9147',
                '66666666666' => 'd0abe942-570d-4387-98e7-de232297c197',
                '333333' => '14dc807a-4d0d-42fd-b019-5574cbb79334',
            );
            if(isset($tmp_arr[$captcha])) {
                $info['bluemember_user_id'] = $tmp_arr[$captcha];
            } else {
                $result = $this->_login($info);
                $info['bluemember_user_id'] = $result['Id'];
            }
            unset($info['captcha']);


            $member = $this->_getMemberInfo($info['bluemember_user_id']);
            $this->_checkMember($member);
            $info['bluemember_info'] = json_encode($member['Content'],JSON_UNESCAPED_UNICODE);
            if(isset($tmp_arr[$captcha])) {
                $info['customer_auth'] = true;
                $info['customer_idnumber'] = '431126199101220100';
            } else {
                $info['customer_auth'] = $member['Content']['SystemMType'] > 1;
                $info['customer_idnumber'] = $member['Content']['IdentityNumber'];
            }

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $info['customer_status'] = STATUS_ACTIVE;
                $info['customer_time_create'] = NOW;
                $info['source'] = $this->input->post('source');
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('创建用户失败!');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else {
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer['customer_auth'] = $info['customer_auth'];
                $customer['customer_idnumber'] = $info['customer_idnumber'];
            }

            $customer['lottery_available'] = $this->m_customer->checkLotteryAvailable($customer['customer_id']);
            $customer['apply_available'] = !$this->m_customer->checkHasApply($customer['customer_id']);

            global $g_marathon_gift;
            $customer['gift_name'] = id2name($customer['gift_type'],$g_marathon_gift);
            $customer['bluemember_user_id_md5'] = md5($customer['bluemember_user_id'].SALT);
            $this->session->set_userdata('marathon_customer',$customer);

            unset($customer['gift_type_tmp']);
            $this->response->setSuccess();
            $this->response->setAddon($customer);
            $this->response->responseExit();
        }

        public function drawnLottery() {
            if(NOW > '2016-08-15 20:00:00') {
                $this->response->setDetail('活动已经结束，请您关注bluemembers的其他活动');
                $this->response->responseExit();
            }

            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_user_id_md5','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['bluemember_user_id_md5'] != md5($info['bluemember_user_id'].SALT)) {
                $this->response->setDetail('请勿恶意访问！');
                $this->response->responseExit();
            }
            unset($info['bluemember_user_id_md5']);

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('不存在该用户！');
                $this->response->responseExit();
            }
            $this->session->set_userdata('marathon_customer',$customer);
            if($customer['customer_auth'] != 1) {
                $this->response->setDetail('认证车主才能抽奖!');
                $this->response->responseExit();
            }

            $lottery_available = $this->m_customer->checkLotteryAvailable($customer['customer_id']);
            if(!$lottery_available) {
                $this->response->setDetail('您已抽过奖!');
                $this->response->responseExit();
            }

            $customer_id = $customer['customer_id'];
            $lottery_result = 0;
            $lottery_time_id=0;
            $lotteryTime = $this->m_lottery_time->getCurrentLotteryTimeRate();
            if(!empty($lotteryTime) && !$this->m_customer->checkHasLotteryGift($customer['customer_id'])) {
                $lottery_time_id = $lotteryTime['lottery_time_id'];
                $lottery_time_gift1_rate = floatval($lotteryTime['lottery_time_gift1_rate']);
                $lottery_time_gift2_rate = floatval($lotteryTime['lottery_time_gift2_rate']);
                $lottery_time_gift3_rate = floatval($lotteryTime['lottery_time_gift3_rate']);
                $lottery_time_gift4_rate = floatval($lotteryTime['lottery_time_gift4_rate']);

                $baseNum = 1000000000;
                $num = rand(1,$baseNum);

                if($customer['gift_type'] == 0) {
                    $rate = 0;
                    $rate += $lottery_time_gift1_rate;
                    if($lottery_result == 0 && $lottery_time_gift1_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift1_count']) > intval($lotteryTime['lottery_time_gift1_count_drawn'])) {
                        $lottery_result = 1;
                    }
                    $rate += $lottery_time_gift2_rate;
                    if($lottery_result == 0 && $lottery_time_gift2_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift2_count']) > intval($lotteryTime['lottery_time_gift2_count_drawn'])) {
                        $lottery_result = 2;
                    }
                    $rate += $lottery_time_gift3_rate;
                    if($lottery_result == 0 && $lottery_time_gift3_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift3_count']) > intval($lotteryTime['lottery_time_gift3_count_drawn'])) {
                        $lottery_result = 3;
                    }
                    $rate += $lottery_time_gift4_rate;
                    if($lottery_result == 0 && $lottery_time_gift4_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift4_count']) > intval($lotteryTime['lottery_time_gift4_count_drawn'])) {
                        $lottery_result = 4;
                    }
                }
            }

            //记录数据库
            $this->m_customer->createLotteryHistory(array(
                'customer_id' => $customer['customer_id'],
                'lottery_time_id' => $lottery_time_id,
                'gift_type' => $lottery_result,
                'lottery_time_time_create' => NOW,
                'source' => $this->input->post('source'),
            ));


            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            if($lottery_result > 0) {
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'gift_type' => $lottery_result,
                    'lottery_time_id' => $lottery_time_id,
                    'customer_time_lottery' => NOW,
                ));
                $this->m_lottery_time->updateLotteryCountDrawn($lottery_time_id,$lottery_result);
            }

            global $g_marathon_gift;
            // $customer = $this->m_customer->getCustomer($customer_id);
            $result = array();
            $result['gift_type'] = $lottery_result;
            $result['gift_name'] = id2name($lottery_result,$g_marathon_gift);
            // $customer['lottery_available'] = $this->m_customer->checkLotteryAvailable($customer['customer_id']);
            // $this->session->set_userdata('marathon_customer',$customer);

            $this->response->setSuccess();
            $this->response->setAddon($result);
            $this->response->responseExit();
        }

        public function authChezhu() {
            if(NOW > '2016-08-15 20:00:00') {
                $this->response->setDetail('活动已经结束，请您关注bluemembers的其他活动');
                $this->response->responseExit();
            }

            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_user_id_md5','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['bluemember_user_id_md5'] != md5($info['bluemember_user_id'].SALT)) {
                $this->response->setDetail('请勿恶意访问！');
                $this->response->responseExit();
            }

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('不存在该用户！');
                $this->response->responseExit();
            }
            $this->session->set_userdata('marathon_customer',$customer);

            if($customer['customer_auth'] == 1) {
                $this->response->setDetail('您已认证车主，不需要再认证了！');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_idnumber','string');
            $this->validate->setRule('customer_idnumber','message','请填写您的身份证信息');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            unset($info['bluemember_user_id_md5']);

            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/Account/ToCheckCarownerSavenew?PaperWork=1&userId='
                .$customer['bluemember_user_id'].'&identityNumber='.$info['customer_idnumber'];
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            $content = json_decode(json_encode($content),true);
            $addon = array();
            if(isset($content['code']) && ($content['code'] == 200 || $content['code'] == 302)) {
                $member = $this->_getMemberInfo($info['bluemember_user_id']);
                $info = array();
                $info['bluemember_info'] = json_encode($member['Content'],JSON_UNESCAPED_UNICODE);
                $info['customer_auth'] = $member['Content']['SystemMType'] > 1;
                $info['customer_idnumber'] = $member['Content']['IdentityNumber'];
                $info['customer_id'] = $customer['customer_id'];
                $info['auth_source'] =  $this->input->post('source');
                $addon['customer_idnumber'] = $member['Content']['IdentityNumber'];
                $this->m_customer->editCustomer($info);
            } else {
                $msg = '';
                if(!empty($content['msg'])) {
                    $msg = $content['msg'];
                } else if(!empty($content['Message'])) {
                    $msg = $content['Message'];
                }
                $this->response->setDetail($msg);
                $this->response->responseExit();
            }

            $this->response->setSuccess();
            $this->response->setDetail('认证成功!');
            $this->response->setAddon($addon);
            $this->response->responseExit();
        }

        public function submitAddress() {
            if(NOW > '2016-08-15 20:00:00') {
                $this->response->setDetail('活动已经结束，请您关注bluemembers的其他活动');
                $this->response->responseExit();
            }
            
            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_user_id_md5','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['bluemember_user_id_md5'] != md5($info['bluemember_user_id'].SALT)) {
                $this->response->setDetail('请勿恶意访问！');
                $this->response->responseExit();
            }

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('不存在该用户！');
                $this->response->responseExit();
            }
            $this->session->set_userdata('marathon_customer',$customer);

            if($customer['gift_type'] == 0) {
                $this->response->setDetail('您还未中奖，不能提交地址!');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_name','message','请填写您的姓名');
            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('customer_phone','message','请填写您的手机号');
            if($customer['gift_type'] == 1) {
                $this->validate->setRule('customer_email','string');
                $this->validate->setRule('customer_email','message','请填写电子邮箱');
            } else {
                $this->validate->setRule('customer_address','string');
                $this->validate->setRule('customer_address','message','请填写您的收货地址');
            }

            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            unset($info['bluemember_user_id']);
            unset($info['bluemember_user_id_md5']);

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            if(isset($info['customer_email'])) {
                if (!filter_var($info['customer_email'], FILTER_VALIDATE_EMAIL)) {
                    $this->response->setDetail('请输入正确的电子邮箱!');
                    $this->response->responseExit();
                }
            }

            $info['customer_id'] = $customer['customer_id'];
            $info['result_source'] = $this->input->post('source');
            $this->m_customer->editCustomer($info);


            $this->response->setSuccess();
            $this->response->setDetail('收货地址提交成功!');
            $this->response->responseExit();
        }

        public function submitApply() {
            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_user_id_md5','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['bluemember_user_id_md5'] != md5($info['bluemember_user_id'].SALT)) {
                $this->response->setDetail('请勿恶意访问！');
                $this->response->responseExit();
            }

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('不存在该用户！');
                $this->response->responseExit();
            }
            $this->session->set_userdata('marathon_customer',$customer);


            $this->validate->setRule('apply_name','string');
            $this->validate->setRule('apply_name','message','请填写姓名');
            $this->validate->setRule('apply_sex','integer');
            $this->validate->setRule('apply_sex','message','请选择性别');
            $this->validate->setRule('apply_blood','string');
            $this->validate->setRule('apply_blood','message','请选择血型');
            $this->validate->setRule('apply_nationality','string');
            $this->validate->setRule('apply_nationality','message','请选择国籍');
            $this->validate->setRule('apply_id_type','integer');
            $this->validate->setRule('apply_id_type','message','请选择证件类型');
            $this->validate->setRule('apply_id_number','string');
            $this->validate->setRule('apply_id_number','message','请填写证件号');
            $this->validate->setRule('apply_birthday','string');
            $this->validate->setRule('apply_birthday','message','请选择出生日期');
            $this->validate->setRule('apply_phone_1','string');
            $this->validate->setRule('apply_phone_1','message','请填写手机号1');
            $this->validate->setRule('apply_phone_2','string');
            $this->validate->setRule('apply_phone_2','message','请填写手机号2');
            $this->validate->setRule('apply_email_1','string');
            $this->validate->setRule('apply_email_1','message','请填写电子邮箱1');
            $this->validate->setRule('apply_email_2','string');
            $this->validate->setRule('apply_email_2','message','请填写电子邮箱2');
            $this->validate->setRule('apply_province','string');
            $this->validate->setRule('apply_province','message','请选择城市');
            $this->validate->setRule('apply_city','string');
            $this->validate->setRule('apply_city','message','请选择城市');
            $this->validate->setRule('apply_district','string');
            $this->validate->setRule('apply_district','message','请选择城市');
            $this->validate->setRule('apply_address','string');
            $this->validate->setRule('apply_address','message','请填写通讯地址');
            $this->validate->setRule('apply_zipcode','string');
            $this->validate->setRule('apply_zipcode','message','请填写邮编');
            $this->validate->setRule('apply_emergency_contact_name','string');
            $this->validate->setRule('apply_emergency_contact_name','message','请填写紧急联系人');
            $this->validate->setRule('apply_emergency_contact_phone','string');
            $this->validate->setRule('apply_emergency_contact_phone','message','请填写紧急联系人电话');
            $this->validate->setRule('apply_job','string');
            $this->validate->setRule('apply_job','message','请填写职业');
            $this->validate->setRule('apply_income','string');
            $this->validate->setRule('apply_income','message','请选择年收入');
            $this->validate->setRule('apply_education','string');
            $this->validate->setRule('apply_education','message','请选择教育程度');
            $this->validate->setRule('apply_past_medical_history','string');
            $this->validate->setRule('apply_past_medical_history','message','请填写既往病史');
            $this->validate->setRule('apply_player_type','string');
            $this->validate->setRule('apply_player_type','message','请选择选手类型');
            $this->validate->setRule('apply_join_game_name','string');
            $this->validate->setRule('apply_join_game_name','message','请填写参加过的赛事');
            $this->validate->setRule('apply_join_game_score','string');
            $this->validate->setRule('apply_join_game_score','message','请完赛成绩');
            $this->validate->setRule('apply_join_last_year','integer');
            $this->validate->setRule('apply_join_last_year','message','请选择一年内时候参加马拉松');
            $this->validate->setRule('apply_join_last_year_name','string');
            $this->validate->setRule('apply_join_last_year_name','notnull',false);
            $this->validate->setRule('apply_join_last_year_name','optional');
            $this->validate->setRule('apply_join_last_year_name','message','请填写一年内最好成绩的赛事');
            $this->validate->setRule('apply_join_last_year_score','string');
            $this->validate->setRule('apply_join_last_year_score','notnull',false);
            $this->validate->setRule('apply_join_last_year_score','optional');
            $this->validate->setRule('apply_join_last_year_score','message','请填写一年内最好成绩');
            $this->validate->setRule('apply_mmunity_organization_1','string');
            $this->validate->setRule('apply_mmunity_organization_1','message','请选择公益组织第一选项');
            $this->validate->setRule('apply_mmunity_organization_2','string');
            $this->validate->setRule('apply_mmunity_organization_2','message','请选择公益组织第二选项');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            unset($info['bluemember_user_id']);
            unset($info['bluemember_user_id_md5']);

            if($customer['gift_type'] != 1) {
                $this->response->setDetail('您没有获得北京马拉松参赛资格!');
                $this->response->responseExit();
            }

            if($this->m_customer->checkHasApply($customer['customer_id'])) {
                $this->response->setDetail('您已经提交申请!');
                $this->response->responseExit();
            }

            if(!preg_match("/^\d{6}$/i", $info['apply_zipcode'])){
                $this->response->setDetail('请输入正确邮编');
                $this->response->responseExit();
            }

            foreach (array('apply_phone_1' => '请输入正确的手机号1','apply_phone_2' => '请输入正确的手机号2'
                ,'apply_emergency_contact_phone' => '请输入正确的紧急联系人电话' ) as $key => $value) {
                if(!preg_match("/^1[0-9]\d{9}$/i", $info[$key])){
                    $this->response->setDetail($value);
                    $this->response->responseExit();
                }
            }
            if(isset($info['apply_join_game_score'])) {
                if(!preg_match("/^\d+:\d+:\d+$/i", $info['apply_join_game_score'])){
                    $this->response->setDetail('请输入正确的完赛成绩,例如: 4:35:20');
                    $this->response->responseExit();
                }
            }
            if($info['apply_join_last_year'] == 1) {
                if(empty($info['apply_join_last_year_name'])) {
                    $this->response->setDetail('请填写一年内最好成绩的赛事');
                    $this->response->responseExit();
                }
                if(empty($info['apply_join_last_year_score']) || !preg_match("/^\d+:\d+:\d+$/i", $info['apply_join_last_year_score'])){
                    $this->response->setDetail('请输入正确一年内最好成绩,例如: 4:35:20');
                    $this->response->responseExit();
                }
            }

            $info['customer_id'] = $customer['customer_id'];
            $info['apply_time_create'] = NOW;
            $info['source'] =  $this->input->post('source');
            $this->m_customer->createApply($info);

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->responseExit();
        }

        public function test() {
        	header("Access-Control-Allow-Origin: *");
        	$this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->responseExit();
        }


        public function dbview() {
            die();
            $data['desc'] = '清除北京马拉松数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }

        public function clearDb(){
            die();
            // $this->db->truncate('bjmarathon_customer');
            // $this->db->truncate('bjmarathon_lottery_history');
            // $this->db->truncate('bjmarathon_apply');

            $this->db->truncate('bjmarathon_customer');
            $this->db->truncate('bjmarathon_lottery_history');
            // $this->db->query("UPDATE `mpc_bjmarathon_customer` SET `gift_type` = '0'");
            $this->db->truncate('bjmarathon_apply');

            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }
    }

}
